/*
 * FunctionDeclAst.cpp
 *
 *  Created on: 19 Nov 2010
 *      Author: kn308
 */

#include <MAlice/Codegen.h>
#include <MAlice/Ast/FunctionDeclAst.h>
#include <MAlice/Ast/FunctionParameterAst.h>
#include <MAlice/Ast/IntegerLiteralAst.h>

namespace MAlice
{

FunctionDeclAst::FunctionDeclAst(FunctionProtoAst* proto, ListAst* body) :
	mProto(proto), mBody(body)
{
}

FunctionDeclAst::~FunctionDeclAst()
{
	delete mProto;
	delete mBody;
}

llvm::Value* FunctionDeclAst::generate()
{
	Codegen* g = Codegen::get();
	// start function scope
	MALICE_AUTO_REVERSE(g);

	// get the function entry from the prototype
	Function* F = reinterpret_cast<Function*> (mProto->generate());
	if (NULL == mBody->generate())
	{
		cerr << "Warning: Function '" << F->getNameStr()
				<< "' seems to contain invalid body." << endl;
	}

	// return the default constructor for all functions
	TypeAst* ret = mProto->getReturnType();
	if (!ret->type()->isVoidTy())
	{
		g->getBuilder()->CreateRet(
				auto_ptr<ExpressionAst>(g->getDefaultValue(ret->getName())).get()->generate());
	}
	else
	{
		g->getBuilder()->CreateRetVoid();
	}

	return F;
}

}
